package org.gw.building.ctrl;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.ArrayUtils;
import org.gw.building.model.*;
import org.gw.building.repositories.*;
import org.gw.building.util.FileHelper;
import org.gw.building.util.TrainUtil;
import org.gw.ylc.base.context.RequestContextHolder;
import org.gw.ylc.base.util.PermissionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

@Controller
@RequestMapping("score")
public class ScoreCtrl {
	@Autowired
	private StuScoreRepository stuScoreRepository;
	@Autowired
	private ScoreSuspendApplyRepository scoreSuspendApplyRepository;
	@Autowired
	private StuInfoRepository stuInfoRepository;
	@Autowired
	private CourseContinueApplyRepository courseContinueApplyRepository;
	@Autowired
	private PrevDelayedExamRepository prevDelayedExamRepository;
	@Autowired
	private CompletionCertReApplyRepository completionCertReApplyRepository;
	@Autowired
	private TermRepository termRepository;

	@RequestMapping("getMyScore")
	@ResponseBody
	public StuScore getMyScore(String term) {
		String uid = RequestContextHolder.get().getUser().getUid();
		StuInfo stuInfo = stuInfoRepository.findOneByXhAndTerm(uid, term);
		return stuScoreRepository.findFirstByStuInfo(stuInfo);
	}

	@RequestMapping("getApply")
	@ResponseBody
	public Object getApply(String term) {
		StuInfo stuInfo = TrainUtil.getCurrentStuInfo(stuInfoRepository, term);
		Map<String, Object> r = new HashMap<String, Object>();
		r.put("suspend", scoreSuspendApplyRepository.findFirstByStuInfo(stuInfo));
		r.put("continue", courseContinueApplyRepository.findFirstByStuInfo(stuInfo));
		r.put("cert", completionCertReApplyRepository.findFirstByStuInfo(stuInfo));
		return r;
	}

	@RequestMapping("applySuspend")
	@ResponseBody
	public Object applySuspend(ScoreSuspendApply suspendApply) {
		StuInfo stuInfo = TrainUtil.getCurrentStuInfo(stuInfoRepository, suspendApply.getStuInfo().getTerm().getId());
		suspendApply.setStuInfo(stuInfo);
		suspendApply.setStatus(1);
		suspendApply.setLxfs(stuInfo.getLxfs());
		return scoreSuspendApplyRepository.save(suspendApply);
	}

	// 续修
	@RequestMapping("continueApply")
	@ResponseBody
	public Object continueApply(CourseContinueApply continueApply) {
		StuInfo stuInfo = TrainUtil.getCurrentStuInfo(stuInfoRepository, continueApply.getStuInfo().getTerm().getId());
		continueApply.setLxfs(stuInfo.getLxfs());
		continueApply.setOriginTerm(stuInfo.getTerm());
		continueApply.setOriginClassInfo(stuInfo.getClassInfo());
		continueApply.setStuInfo(stuInfo);
		continueApply.setStatus(1);
		return courseContinueApplyRepository.save(continueApply);
	}

	@RequestMapping("reApplyCert")
	@ResponseBody
	public Object reApplyCert(CompletionCertReApply apply) {
		StuInfo stuInfo = TrainUtil.getCurrentStuInfo(stuInfoRepository, apply.getStuInfo().getTerm().getId());
		apply.setStuInfo(stuInfo);
		apply.setLxfs(stuInfo.getLxfs());
		apply.setStatus(1);
		return completionCertReApplyRepository.save(apply);
	}

	/////////////////////////////////////////////////////////////////////////////
	//
	// 成绩
	//
	/////////////////////////////////////////////////////////////////////////////
	@RequestMapping("queryScore")
	@ResponseBody
	public Page<StuScore> queryScore(String term, String name, String department, String clazz, Integer isTzs,
			String khjg) {
		return stuScoreRepository.query(term, name, PermissionUtil.getFilteredDepartmentId(department), clazz, isTzs, khjg,
				RequestContextHolder.get().getPageRequest());
	}

	@RequestMapping("addScore")
	@ResponseBody
	public Object addScore(StuScore score) {
		if (score.getStuInfo() == null) {
			return null;
		}
		return stuScoreRepository.save(score);
	}

	// 导入
	@RequestMapping("importScore")
	@ResponseBody
	public Object importScore(MultipartFile file, Term term) throws Exception {
		File tempFolder = FileHelper.getTempFolder("train_");
		String xlsFilePath = tempFolder.getAbsolutePath() + "/" + file.getOriginalFilename();
		File xlsFile = new File(xlsFilePath);
		FileUtils.copyInputStreamToFile(file.getInputStream(), xlsFile);
		return doImportScore(xlsFile, term);
	}

	private final static List<String> SCORE_IMP_HEADERS = Arrays
			.asList(new String[] { "学号", "必修课", "选修课", "体验课", "选择题", "主观题", "考核结果" });

	private String doImportScore(File xlsFile, Term term) throws BiffException, IOException {
		Workbook workbook = Workbook.getWorkbook(xlsFile);
		Sheet sheet = workbook.getSheet(0);
		int rows = sheet.getRows();
		int columns = sheet.getColumns();
		/** Main content */
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		/** Headers */
		// ["学号"、"必修课", "选修课", "体验课", "选择题", "主观题", "考核结果"]
		List<String> headers = new ArrayList<String>();
		for (int row = 0; row < rows; row++) {
			Map<String, String> map = new LinkedHashMap<String, String>();
			for (int col = 0; col < columns; col++) {
				String s = sheet.getCell(col, row).getContents();
				if (row == 0) {
					headers.add(s != null ? s.trim().toLowerCase() : "");
				} else {
					map.put(headers.get(col), s != null ? s.trim() : "");
				}
			}
			if (row != 0)
				list.add(map);
		}
		// 校验header
		if (!ArrayUtils.isEquals(headers, SCORE_IMP_HEADERS)) {
			return "导入的文件中的表头不正确，应该是：" + SCORE_IMP_HEADERS;
		}
		// 逐行处理数据
		StringBuffer message = new StringBuffer();
		final List<StuScore> allList = new ArrayList<StuScore>();
		for (Map<String, String> row : list) {
			String xh = row.get("学号");
			String bxk = row.get("必修课");
			String xxk = row.get("选修课");
			String tyk = row.get("体验课");
			String xzt = row.get("选择题");
			String zgt = row.get("主观题");
			String khjg = row.get("考核结果");
			StuInfo stuInfo = stuInfoRepository.findOneByXhAndTerm(xh, term.getId());
			if (stuInfo == null) {
				message.append("学号" + xh + "不存在\n");
				continue;
			}
			StuScore score = stuScoreRepository.findFirstByStuInfo(stuInfo);
			if (score == null) {
				// 学生成绩不存在
				score = new StuScore();
				score.setStuInfo(stuInfo);
			}
			score.setBxk(bxk);
			score.setXxk(xxk);
			score.setTyk(tyk);
			score.setXzt(xzt);
			score.setZgt(zgt);
			score.setKhjg(khjg);
			allList.add(score);
		}
		if (allList.size() > 0) {
			stuScoreRepository.save(new Iterable<StuScore>() {
				@Override
				public Iterator<StuScore> iterator() {
					return allList.iterator();
				}
			});
		}
		return message.toString();
	}

	// 导出
	@RequestMapping("exportScore")
	@ResponseBody
	public Object exportScore(String term, HttpServletResponse response)
			throws FileNotFoundException, IOException, RowsExceededException, WriteException {
		Page<StuScore> cList = stuScoreRepository.query(term, null, null, null, null, null,
				new PageRequest(0, Integer.MAX_VALUE));
		File tempFolder = FileHelper.getTempFolder("train_");
		String xlsFileName = "学生成绩信息.xls";
		String xlsFilePath = tempFolder.getAbsolutePath() + "/" + xlsFileName;
		File xlsFile = new File(xlsFilePath);
		response.setContentType("application/octet-stream;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(xlsFileName, "UTF-8"));
		doExportScore(xlsFile, cList.getContent());
		OutputStream out = response.getOutputStream();
		FileCopyUtils.copy(new FileInputStream(xlsFile), out);
		out.flush();
		return null;
	}

	private void doExportScore(File xlsFile, List<StuScore> cList)
			throws IOException, RowsExceededException, WriteException {
		WritableWorkbook book = null;
		String[] headers = { "期数", "姓名", "学号", "年级", "院系", "所属班级", "学生类别", "联系电话", "校区", "是否团支书", "必修课", "选修课", "体验课",
				"选择题", "主观题", "总计", "考核结果" };
		try {
			book = Workbook.createWorkbook(xlsFile);
			WritableSheet sheet = book.createSheet("学生成绩信息", 0);
			/** 写header */
			for (int i = 0; i < headers.length; i++) {
				sheet.addCell(new Label(i, 0, headers[i]));
			}
			int row = 1;
			for (StuScore c : cList) {
				StuInfo stu = c.getStuInfo();
				sheet.addCell(new Label(0, row, stu.getTerm().getName()));
				sheet.addCell(new Label(1, row, stu.getUser().getName()));
				sheet.addCell(new Label(2, row, stu.getUser().getUid()));
				sheet.addCell(new Label(3, row, stu.getUser().getGrade()));
				sheet.addCell(new Label(4, row, stu.getUser().getDepartment()));
				sheet.addCell(new Label(5, row, stu.getClassInfo().getBjName()));
				sheet.addCell(new Label(6, row, ""));// TODO: 学生类别
				sheet.addCell(new Label(7, row, stu.getLxfs()));
				sheet.addCell(new Label(8, row, stu.getXq()));
				sheet.addCell(new Label(9, row, stu.getSfwtzs() == 1 ? "是" : "否"));
				sheet.addCell(new Label(10, row, c.getBxk()));
				sheet.addCell(new Label(11, row, c.getXxk()));
				sheet.addCell(new Label(12, row, c.getTyk()));
				sheet.addCell(new Label(13, row, c.getXzt()));
				sheet.addCell(new Label(14, row, c.getZgt()));
				sheet.addCell(new Label(15, row, c.getXzt() + c.getZgt()));
				sheet.addCell(new Label(16, row, c.getKhjg()));
				row += 1;
			}
			book.write();
		} finally {
			if (book != null)
				try {
					book.close();
				} catch (WriteException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

	/////////////////////////////////////////////////////////////////////////////
	//
	// 缓考
	//
	/////////////////////////////////////////////////////////////////////////////
	@RequestMapping("queryDelayed")
	@ResponseBody
	public Page<PrevDelayedExam> queryDelayed(String term, String name, String department, String clazz,
			Integer isTzs) {
		return prevDelayedExamRepository.query(term, PermissionUtil.toLikeString(name), PermissionUtil.getFilteredDepartmentId(department), clazz, isTzs,
				RequestContextHolder.get().getPageRequest());
	}

	@RequestMapping("addDelayed")
	@ResponseBody
	public Object addDelayed(PrevDelayedExam delayedExam) {
		prevDelayedExamRepository.save(delayedExam);
		StuScore stuScore = stuScoreRepository.findFirstByStuInfo(delayedExam.getStuInfo());
		if (stuScore == null) {
			stuScore = new StuScore();
			stuScore.setStuInfo(delayedExam.getStuInfo());
		}
		stuScore.setXzt(delayedExam.getXzt());
		stuScore.setZgt(delayedExam.getZgt());
		stuScore.setZj(delayedExam.getZj());
		// stuScore.setBxk(null);
		// stuScore.setXxk(null);
		// stuScore.setTyk(null);
		stuScoreRepository.save(stuScore);
		return "success";
	}

	// 导入
	@RequestMapping("importDelayed")
	@ResponseBody
	public Object importDelayed(MultipartFile file, String term) throws Exception {
		File tempFolder = FileHelper.getTempFolder("train_");
		String xlsFilePath = tempFolder.getAbsolutePath() + "/" + file.getOriginalFilename();
		File xlsFile = new File(xlsFilePath);
		FileUtils.copyInputStreamToFile(file.getInputStream(), xlsFile);
		return doImportDelayed(xlsFile, term);
	}

	private final static List<String> SCORE_DELAYED_IMP_HEADERS = Arrays.asList(new String[] { "学号", "选择题", "主观题" });

	private String doImportDelayed(File xlsFile, String term) throws BiffException, IOException {
		Workbook workbook = Workbook.getWorkbook(xlsFile);
		Sheet sheet = workbook.getSheet(0);
		int rows = sheet.getRows();
		int columns = sheet.getColumns();
		/** Main content */
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		/** Headers */
		// ["学号", "选择题", "主观题"]
		List<String> headers = new ArrayList<String>();
		for (int row = 0; row < rows; row++) {
			Map<String, String> map = new LinkedHashMap<String, String>();
			for (int col = 0; col < columns; col++) {
				String s = sheet.getCell(col, row).getContents();
				if (row == 0) {
					headers.add(s != null ? s.trim().toLowerCase() : "");
				} else {
					map.put(headers.get(col), s != null ? s.trim() : "");
				}
			}
			if (row != 0)
				list.add(map);
		}
		// 校验header
		if (!ArrayUtils.isEquals(headers, SCORE_DELAYED_IMP_HEADERS)) {
			return "导入的文件中的表头不正确，应该是：" + SCORE_DELAYED_IMP_HEADERS;
		}
		// 逐行处理数据
		StringBuffer message = new StringBuffer();
		final List<PrevDelayedExam> allList = new ArrayList<PrevDelayedExam>();
		for (Map<String, String> row : list) {
			String xh = row.get("学号");
			String xzt = row.get("选择题");
			String zgt = row.get("主观题");
			StuInfo stuInfo = stuInfoRepository.findOneByXhAndTerm(xh, term);
			if (stuInfo == null) {
				message.append("学号" + xh + "不存在\n");
				continue;
			}
			PrevDelayedExam score = prevDelayedExamRepository.findFirstByStuInfo(stuInfo);
			if (score == null) {
				// 缓考成绩不存在
				score = new PrevDelayedExam();
				score.setStuInfo(stuInfo);
			}
			score.setXzt(xzt);
			score.setZgt(zgt);
			allList.add(score);
		}
		if (allList.size() > 0) {
			prevDelayedExamRepository.save(new Iterable<PrevDelayedExam>() {
				@Override
				public Iterator<PrevDelayedExam> iterator() {
					return allList.iterator();
				}
			});
		}
		return message.toString();
	}

	// 导出
	@RequestMapping("exportDelayed")
	@ResponseBody
	public Object exportDelayed(String term, HttpServletResponse response)
			throws FileNotFoundException, IOException, RowsExceededException, WriteException {
		Page<PrevDelayedExam> cList = prevDelayedExamRepository.query(term, null, null, null, null,
				new PageRequest(0, Integer.MAX_VALUE));
		File tempFolder = FileHelper.getTempFolder("train_");
		String xlsFileName = "往期缓考信息.xls";
		String xlsFilePath = tempFolder.getAbsolutePath() + "/" + xlsFileName;
		File xlsFile = new File(xlsFilePath);
		response.setContentType("application/octet-stream;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(xlsFileName, "UTF-8"));
		doExportDelayed(xlsFile, cList.getContent());
		OutputStream out = response.getOutputStream();
		FileCopyUtils.copy(new FileInputStream(xlsFile), out);
		out.flush();
		return null;
	}

	private void doExportDelayed(File xlsFile, List<PrevDelayedExam> cList)
			throws IOException, RowsExceededException, WriteException {
		WritableWorkbook book = null;
		String[] headers = { "期数", "姓名", "学号", "年级", "院系", "所属班级", "学生类别", "联系电话", "校区", "是否团支书", "选择题", "主观题", "总计" };
		try {
			book = Workbook.createWorkbook(xlsFile);
			WritableSheet sheet = book.createSheet("往期缓考信息", 0);
			/** 写header */
			for (int i = 0; i < headers.length; i++) {
				sheet.addCell(new Label(i, 0, headers[i]));
			}
			int row = 1;
			for (PrevDelayedExam c : cList) {
				StuInfo stu = c.getStuInfo();
				sheet.addCell(new Label(0, row, stu.getTerm().getName()));
				sheet.addCell(new Label(1, row, stu.getUser().getName()));
				sheet.addCell(new Label(2, row, stu.getUser().getUid()));
				sheet.addCell(new Label(3, row, stu.getUser().getGrade()));
				sheet.addCell(new Label(4, row, stu.getUser().getDepartment()));
				sheet.addCell(new Label(5, row, stu.getClassInfo().getBjName()));
				sheet.addCell(new Label(6, row, ""));// TODO: 学生类别
				sheet.addCell(new Label(7, row, stu.getLxfs()));
				sheet.addCell(new Label(8, row, stu.getXq()));
				sheet.addCell(new Label(9, row, stu.getSfwtzs() == 1 ? "是" : "否"));
				sheet.addCell(new Label(10, row, c.getXzt()));
				sheet.addCell(new Label(11, row, c.getZgt()));
				sheet.addCell(new Label(12, row, c.getXzt() + c.getZgt()));
				row += 1;
			}
			book.write();
		} finally {
			if (book != null)
				try {
					book.close();
				} catch (WriteException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

	/////////////////////////////////////////////////////////////////////////////
	//
	// 保留成绩
	//
	/////////////////////////////////////////////////////////////////////////////
	@RequestMapping("querySuspend")
	@ResponseBody
	public Page<ScoreSuspendApply> querySuspend(String term, String name, String department, String clazz,
			Integer isTzs, Integer status) {
		return scoreSuspendApplyRepository.query(term, PermissionUtil.toLikeString(name), PermissionUtil.getFilteredDepartmentId(department), clazz, isTzs,
				PermissionUtil.getFilteredStatus(status), RequestContextHolder.get().getPageRequest());
	}

	@RequestMapping("auditSuspend")
	@ResponseBody
	public Object auditSuspend(ScoreSuspendApply delayedExam, boolean pass) {
		if (delayedExam != null && PermissionUtil.getFilteredStatus(null) == delayedExam.getStatus()) {
			int status = delayedExam.getStatus() + 1;
			if (!pass) {
				status = -1;
			}
			delayedExam.setStatus(status);
			scoreSuspendApplyRepository.save(delayedExam);
			if (status == 3) {
				StuInfo stuInfo = delayedExam.getStuInfo();
				stuInfo = stuInfoRepository.findOne(stuInfo.getId());
				stuInfo.setStatus(1);
				stuInfoRepository.save(stuInfo);
			}
			return "success";
		}
		return null;
	}

	@RequestMapping("batchAuditSuspend")
	@ResponseBody
	@Transactional
	public Object batchAuditSuspend(String ids, boolean pass) {
		Iterable<ScoreSuspendApply> all = scoreSuspendApplyRepository.findAll(Arrays.asList(ids));
		for (ScoreSuspendApply delayedExam : all) {
			if (delayedExam != null && PermissionUtil.getFilteredStatus(null) == delayedExam.getStatus()) {
				int status = delayedExam.getStatus() + 1;
				if (!pass) {
					status = -1;
				}
				delayedExam.setStatus(status);
				if (status == 3) {
					StuInfo stuInfo = delayedExam.getStuInfo();
					stuInfo = stuInfoRepository.findOne(stuInfo.getId());
					stuInfo.setStatus(1);
					stuInfoRepository.save(stuInfo);
				}
			}
		}
		scoreSuspendApplyRepository.save(all);
		return "success";
	}

	@RequestMapping("exportSuspend")
	@ResponseBody
	public Object exportSuspend(String term, HttpServletResponse response)
			throws FileNotFoundException, IOException, RowsExceededException, WriteException {
		Page<ScoreSuspendApply> cList = scoreSuspendApplyRepository.query(term, null, null, null, null, null,
				new PageRequest(0, Integer.MAX_VALUE));
		File tempFolder = FileHelper.getTempFolder("train_");
		String xlsFileName = "保留成绩申请信息.xls";
		String xlsFilePath = tempFolder.getAbsolutePath() + "/" + xlsFileName;
		File xlsFile = new File(xlsFilePath);
		response.setContentType("application/octet-stream;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(xlsFileName, "UTF-8"));
		doExportSuspend(xlsFile, cList.getContent());
		OutputStream out = response.getOutputStream();
		FileCopyUtils.copy(new FileInputStream(xlsFile), out);
		out.flush();
		return null;
	}

	private void doExportSuspend(File xlsFile, List<ScoreSuspendApply> cList)
			throws IOException, RowsExceededException, WriteException {
		WritableWorkbook book = null;
		String[] headers = { "期数", "姓名", "学号", "院系", "所属班级", "保留期限", "联系电话", "申请原因", "审核状态" };
		try {
			book = Workbook.createWorkbook(xlsFile);
			WritableSheet sheet = book.createSheet("保留成绩申请信息", 0);
			/** 写header */
			for (int i = 0; i < headers.length; i++) {
				sheet.addCell(new Label(i, 0, headers[i]));
			}
			int row = 1;
			for (ScoreSuspendApply c : cList) {
				StuInfo stu = c.getStuInfo();
				sheet.addCell(new Label(0, row, stu.getTerm().getName()));
				sheet.addCell(new Label(1, row, stu.getUser().getName()));
				sheet.addCell(new Label(2, row, stu.getUser().getUid()));
				sheet.addCell(new Label(3, row, stu.getUser().getDepartment()));
				sheet.addCell(new Label(4, row, stu.getClassInfo().getBjName()));
				sheet.addCell(new Label(5, row, c.getBlqx()));
				sheet.addCell(new Label(6, row, c.getLxfs()));
				sheet.addCell(new Label(7, row, c.getSqyy()));
				sheet.addCell(new Label(8, row, c.getStatus().toString()));
				row += 1;
			}
			book.write();
		} finally {
			if (book != null)
				try {
					book.close();
				} catch (WriteException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

	/////////////////////////////////////////////////////////////////////////////
	//
	// 续修
	//
	/////////////////////////////////////////////////////////////////////////////
	@RequestMapping("queryContinue")
	@ResponseBody
	public Page<CourseContinueApply> queryContinue(String term, String name, String department, String clazz,
			Integer isTzs, Integer status) {
		return courseContinueApplyRepository.query(term, PermissionUtil.toLikeString(name), PermissionUtil.getFilteredDepartmentId(department), clazz, isTzs,
				PermissionUtil.getFilteredStatus(status), RequestContextHolder.get().getPageRequest());
	}

	@RequestMapping("auditContinue")
	@ResponseBody
	public Object auditContinue(CourseContinueApply continueApply, boolean pass) {
		if (continueApply != null && PermissionUtil.getFilteredStatus(null) == continueApply.getStatus()) {
			int status = continueApply.getStatus() + 1;
			if (!pass) {
				status = -1;
			}
			continueApply.setStatus(status);
			courseContinueApplyRepository.save(continueApply);
			if (status == 3) {
				StuInfo stuInfo = continueApply.getStuInfo();
				stuInfo = stuInfoRepository.findOne(stuInfo.getId());
				stuInfo.setTerm(termRepository.getCurrentTerm(continueApply.getOriginTerm().getTrainType().getId()));
				stuInfo.setStatus(0);
				stuInfoRepository.save(stuInfo);
			}
			return "success";
		}
		return null;
	}

	@RequestMapping("batchAuditContinue")
	@ResponseBody
	public Object batchAuditContinue(String ids, boolean pass) {
		Iterable<CourseContinueApply> all = courseContinueApplyRepository.findAll(Arrays.asList(ids));
		for (CourseContinueApply continueApply : all) {
			if (continueApply != null && PermissionUtil.getFilteredStatus(null) == continueApply.getStatus()) {
				int status = continueApply.getStatus() + 1;
				if (!pass) {
					status = -1;
				}
				continueApply.setStatus(status);
				if (status == 3) {
					StuInfo stuInfo = continueApply.getStuInfo();
					stuInfo = stuInfoRepository.findOne(stuInfo.getId());
					stuInfo.setStatus(0);
					stuInfo.setTerm(
							termRepository.getCurrentTerm(continueApply.getOriginTerm().getTrainType().getId()));
					stuInfoRepository.save(stuInfo);
				}
			}
		}
		courseContinueApplyRepository.save(all);
		return "success";
	}

	@RequestMapping("exportContinue")
	@ResponseBody
	public Object exportContinue(String term, HttpServletResponse response)
			throws FileNotFoundException, IOException, RowsExceededException, WriteException {
		Page<CourseContinueApply> cList = courseContinueApplyRepository.query(term, null, null, null, null, null,
				new PageRequest(0, Integer.MAX_VALUE));
		File tempFolder = FileHelper.getTempFolder("train_");
		String xlsFileName = "续修课程申请信息.xls";
		String xlsFilePath = tempFolder.getAbsolutePath() + "/" + xlsFileName;
		File xlsFile = new File(xlsFilePath);
		response.setContentType("application/octet-stream;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(xlsFileName, "UTF-8"));
		doExportContinue(xlsFile, cList.getContent());
		OutputStream out = response.getOutputStream();
		FileCopyUtils.copy(new FileInputStream(xlsFile), out);
		out.flush();
		return null;
	}

	private void doExportContinue(File xlsFile, List<CourseContinueApply> cList)
			throws IOException, RowsExceededException, WriteException {
		WritableWorkbook book = null;
		String[] headers = { "期数", "姓名", "学号", "院系", "所属班级", "联系电话", "续修原因", "审核状态" };
		try {
			book = Workbook.createWorkbook(xlsFile);
			WritableSheet sheet = book.createSheet("续修课程申请信息", 0);
			/** 写header */
			for (int i = 0; i < headers.length; i++) {
				sheet.addCell(new Label(i, 0, headers[i]));
			}
			int row = 1;
			for (CourseContinueApply c : cList) {
				StuInfo stu = c.getStuInfo();
				sheet.addCell(new Label(0, row, stu.getTerm().getName()));
				sheet.addCell(new Label(1, row, stu.getUser().getName()));
				sheet.addCell(new Label(2, row, stu.getUser().getUid()));
				sheet.addCell(new Label(3, row, stu.getUser().getDepartment()));
				sheet.addCell(new Label(4, row, stu.getClassInfo().getBjName()));
				sheet.addCell(new Label(5, row, c.getLxfs()));
				sheet.addCell(new Label(6, row, c.getSqyy()));
				sheet.addCell(new Label(7, row, c.getStatus().toString()));
				row += 1;
			}
			book.write();
		} finally {
			if (book != null)
				try {
					book.close();
				} catch (WriteException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

	/////////////////////////////////////////////////////////////////////////////
	//
	// 结业证补办
	//
	/////////////////////////////////////////////////////////////////////////////
	@RequestMapping("queryCertReApply")
	@ResponseBody
	public Page<CompletionCertReApply> queryCertReApply(String term, String name, String department, String clazz,
			Integer isTzs, Integer status) {
		return completionCertReApplyRepository.query(term, PermissionUtil.toLikeString(name), department, clazz, isTzs,
				PermissionUtil.getFilteredStatus(status), RequestContextHolder.get().getPageRequest());
	}

	@RequestMapping("auditCertReApply")
	@ResponseBody
	public Object auditCertReApply(CompletionCertReApply certReApply, boolean pass) {
		if (certReApply != null && PermissionUtil.getFilteredStatus(null) == certReApply.getStatus()) {
			int status = certReApply.getStatus() + 1;
			if (!pass) {
				status = -1;
			}
			certReApply.setStatus(status);
			completionCertReApplyRepository.save(certReApply);
			return "success";
		}
		return null;
	}

	@RequestMapping("batchAuditCertReApply")
	@ResponseBody
	public Object batchAuditCertReApply(String ids, boolean pass) {
		Iterable<CompletionCertReApply> all = completionCertReApplyRepository.findAll(Arrays.asList(ids));
		for (CompletionCertReApply delayedExam : all) {
			if (delayedExam != null && PermissionUtil.getFilteredStatus(null) == delayedExam.getStatus()) {
				int status = delayedExam.getStatus() + 1;
				if (!pass) {
					status = -1;
				}
				delayedExam.setStatus(status);
			}
		}
		completionCertReApplyRepository.save(all);
		return "success";
	}

	@RequestMapping("exportCertReApply")
	@ResponseBody
	public Object exportCertReApply(String term, HttpServletResponse response)
			throws FileNotFoundException, IOException, RowsExceededException, WriteException {
		Page<CompletionCertReApply> cList = completionCertReApplyRepository.query(term, null, null, null, null, null,
				new PageRequest(0, Integer.MAX_VALUE));
		File tempFolder = FileHelper.getTempFolder("train_");
		String xlsFileName = "结业证补办申请信息.xls";
		String xlsFilePath = tempFolder.getAbsolutePath() + "/" + xlsFileName;
		File xlsFile = new File(xlsFilePath);
		response.setContentType("application/octet-stream;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(xlsFileName, "UTF-8"));
		doExportCertReApply(xlsFile, cList.getContent());
		OutputStream out = response.getOutputStream();
		FileCopyUtils.copy(new FileInputStream(xlsFile), out);
		out.flush();
		return null;
	}

	private void doExportCertReApply(File xlsFile, List<CompletionCertReApply> cList)
			throws IOException, RowsExceededException, WriteException {
		WritableWorkbook book = null;
		String[] headers = { "期数", "姓名", "学号", "院系", "所属班级", "联系电话", "补办原因", "审核状态" };
		try {
			book = Workbook.createWorkbook(xlsFile);
			WritableSheet sheet = book.createSheet("结业证补办申请信息", 0);
			/** 写header */
			for (int i = 0; i < headers.length; i++) {
				sheet.addCell(new Label(i, 0, headers[i]));
			}
			int row = 1;
			for (CompletionCertReApply c : cList) {
				StuInfo stu = c.getStuInfo();
				sheet.addCell(new Label(0, row, stu.getTerm().getName()));
				sheet.addCell(new Label(1, row, stu.getUser().getName()));
				sheet.addCell(new Label(2, row, stu.getUser().getUid()));
				sheet.addCell(new Label(3, row, stu.getUser().getDepartment()));
				sheet.addCell(new Label(4, row, stu.getClassInfo().getBjName()));
				sheet.addCell(new Label(5, row, c.getLxfs()));
				sheet.addCell(new Label(6, row, c.getSqyy()));
				sheet.addCell(new Label(7, row, c.getStatus().toString()));
				row += 1;
			}
			book.write();
		} finally {
			if (book != null)
				try {
					book.close();
				} catch (WriteException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

}
